<template>
  <!-- 情况一：添加/修改 -->
  <el-table
    :data="isBatch ? skuList : skusRuleData!"
    border
    class="tabNumWidth"
    max-height="500"
    size="small"
  >
    <template v-if="formData!.specType && !isBatch">
      <!--  根据商品属性动态添加 -->
      <el-table-column
        v-for="(item, index) in tableHeaders"
        :key="index"
        :label="item.label"
        align="center"
        fixed="left"
        width="120"
      >
        <template #default="{ row }">
          <span style="font-weight: bold; color: #40aaff">
            {{ row.properties[index]?.valueName }}
          </span>
        </template>
      </el-table-column>
    </template>
    <el-table-column
      align="center"
      :label="dict.spuName"
      v-for="(dict, dictIndex) in paidMembershipLevelList"
      :key="dictIndex"
      width="300"
    >
      <!-- v-if="ruleType != 'coupon'" 非优惠券 -->
      <template #default="{ row }">
        <el-input
          v-model="row['ruleValue'][dict.spuId]['discount']"
          :formatter="
            (value: string) =>
              handleFormatterDiscountPrice(row['ruleValue'][dict.spuId]['type'], value)
          "
        >
          <template #prepend>
            <el-select v-model="row['ruleValue'][dict.spuId]['type']" class="w120px!">
              <el-option
                v-for="(item, index) in selectTypeList"
                :label="item.typeName"
                :value="item.typeCode"
                :key="index"
              />
            </el-select>
          </template>
          <template #append>
            <span v-if="integralType.includes(ruleType)">
              {{ row['ruleValue'][dict.spuId]['type'] == 0 ? '%' : '个' }}
            </span>

            <span v-if="deduType.includes(ruleType)"> 元 </span>
            <span v-if="discountType.includes(ruleType)">
              {{ row['ruleValue'][dict.spuId]['type'] == 0 ? '%' : '元' }}
            </span>
          </template>
        </el-input>
      </template>
      <!-- <template #default="{ row }" v-else>
        <el-button
          v-if="row[`${ruleType}${dict.value}`]?.length == 0"
          @click="handleAddCoupon(row, `${ruleType}${dict.value}`)"
          >添加代金券</el-button
        >
        <el-popover placement="right" :width="800" trigger="click" v-else>
          <template #reference>
            <el-button>已关联{{ row[`${ruleType}${dict.value}`].length }}张代金券</el-button>
          </template>
          <CouponList
            v-model:multiple-selection="row[`${ruleType}${dict.value}`]"
            :is-detail="isDetail"
            class="mt-20px"
          >
            <template #extension>
              <el-table-column align="center" label="关联数量" prop="number" min-width="168">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.number"
                    :disabled="isDetail"
                    :min="0"
                    :precision="0"
                    :step="1"
                    class="w-120px!"
                    :controls="false"
                    controls-position="right"
                  />
                </template>
              </el-table-column>
            </template>
          </CouponList>
        </el-popover>
      </template> -->
    </el-table-column>

    <el-table-column
      v-if="formData?.specType && isBatch"
      align="center"
      fixed="right"
      label="操作"
      width="80"
    >
      <template #default>
        <el-button link size="small" type="primary" @click="batchAdd"> 批量添加 </el-button>
        <!-- <el-button v-else link size="small" type="primary" @click="deleteSku(row)">删除</el-button> -->
      </template>
    </el-table-column>
  </el-table>

  <!-- <CouponSelect ref="couponSelectDialog" v-model:multiple-selection="couponList">
    <template #extension>
      <el-table-column align="center" label="关联数量" prop="number" min-width="168">
        <template #default="{ row }">
          <el-input-number
            v-model="row.number"
            :min="0"
            :precision="0"
            :step="1"
            class="w-120px!"
            controls-position="right"
          />
        </template>
      </el-table-column>
    </template>
  </CouponSelect> -->
</template>
<script lang="ts" setup>
import { PropType, Ref } from 'vue'
import { copyValueToTarget } from '@/utils'
import { propTypes } from '@/utils/propTypes'
import type { Sku, Spu } from '@/api/mall/product/spu'
import { RuleConfig } from '@/views/mall/product/spu/components/index'
import { PropertyAndValues } from './index'
import { ElTable } from 'element-plus'
import { isEmpty } from '@/utils/is'
import { cloneDeep } from 'lodash-es'
import { verifyNumberIntegerAndFloat, verifyNumberPercentage } from '@/utils/formatter'

// import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
// import { CouponList } from '@/views/mall/product/spu/components/index'

defineOptions({ name: 'SkuListPaidMemberShip' })
const message = useMessage() // 消息弹窗

const props = defineProps({
  propFormData: {
    type: Object as PropType<Spu>,
    default: () => {}
  },
  propertyList: {
    type: Array as PropType<PropertyAndValues[]>,
    default: () => []
  },
  ruleConfig: {
    type: Array as PropType<RuleConfig[]>,
    default: () => []
  },
  paidMembershipLevelList: {
    type: Array as PropType<any[]>,
    default: () => []
  },
  selectTypeList: {
    type: Array as PropType<any[]>,
    default: () => []
  },
  ruleType: propTypes.string.def(''), //会员规则类型
  valueType: propTypes.string.def(''), //数据字段Key
  isBatch: propTypes.bool.def(false) // 是否作为批量操作组件
})
const formData: Ref<Spu | undefined> = ref<Spu>() // 表单数据
const skusRuleData = ref<any>([]) //需要填写的列表

const skuList = ref<Sku[]>([]) // 批量添加时的临时数据
const integralType = ['paidmemberPointsGain'] //比例 固定积分
const deduType = ['deduPaidmemberIntegral', 'paidmemberWalletRule']
const discountType = ['paidmemberDiscount'] //比例 固定金额
const emit = defineEmits<{
  (e: 'update:modelValue', v: any)
}>()
/** 处理优惠输入限制 */

const handleFormatterDiscountPrice = (type, value: string) => {
  if (type == 0) {
    return verifyNumberPercentage(value)
  } else {
    return verifyNumberIntegerAndFloat(value)
  }
}
/** 批量添加 */
const batchAdd = () => {
  validateProperty()
  skusRuleData.value.forEach((item) => {
    copyValueToTarget(item, skuList.value[0])
  })
  formData.value![props.valueType] = arrayToObject(skusRuleData.value)
}
const objectToArray = (obj) => {
  return Object.keys(obj).map(function (key) {
    return { skuId: key, ruleValue: obj[key] }
  })
}
const arrayToObject = (arr) => {
  return arr.reduce(function (obj, item) {
    obj[item.skuId] = item.ruleValue
    return obj
  }, {})
}
/** 校验商品属性属性值 */
const validateProperty = () => {
  // 校验商品属性属性值是否为空，有一个为空都不给过
  const warningInfo = '存在属性属性值为空，请先检查完善属性值后重试！！！'
  for (const item of props.propertyList) {
    if (!item.values || isEmpty(item.values)) {
      message.warning(warningInfo)
      throw new Error(warningInfo)
    }
  }
}

const tableHeaders = ref<{ prop: string; label: string }[]>([]) // 多属性表头
/**
 * 保存时，每个商品规格的表单要校验下。例如说，销售金额最低是 0.01 这种。
 */
const validateSku = () => {
  formData.value![props.valueType] = arrayToObject(skusRuleData.value)

  // validateProperty()
  // let warningInfo = '请检查商品各行相关属性配置，'
  // let validate = true // 默认通过
  // for (const sku of formData.value!.skus!) {
  //   // 作为活动组件的校验
  //   for (const rule of props?.ruleConfig) {
  //     const arg = getValue(sku, rule.name)

  //     if (!rule.rule(arg)) {
  //       validate = false // 只要有一个不通过则直接不通过
  //       warningInfo += rule.message
  //       break
  //     }
  //   }
  //   // 只要有一个不通过则结束后续的校验
  //   if (!validate) {
  //     message.warning(warningInfo)
  //     throw new Error(warningInfo)
  //   }
  // }
}

// 添加优惠券
// import CouponSelect from '@/views/mall/promotion/coupon/components/CouponSelect.vue'
// const operateRow = ref() //操作的行
// const operateRowKey = ref() //操作的行Key

// import * as CouponTemplateApi from '@/api/mall/promotion/coupon/couponTemplate'
// const couponList = ref<CouponTemplateApi.CouponTemplateVO[]>([])
// const couponSelectDialog = ref()
// const handleAddCoupon = (row: any, key: any) => {
//   operateRow.value = row
//   operateRowKey.value = key
//   couponSelectDialog.value.open()
// }
// watch(
//   () => couponList.value,
//   () => {
//     operateRow.value[operateRowKey.value] = couponList.value
//   }
// )

/**
 * 将传进来的值赋值给 skuList
 */
watch(
  () => props.propFormData,
  (data) => {
    if (!data) return

    formData.value = data

    let deepCopyFormData = cloneDeep(formData.value.skus)

    deepCopyFormData?.forEach((ele: any) => {
      ele.ruleValue = {}
      props.paidMembershipLevelList.forEach((dict) => {
        ele.ruleValue[dict.spuId] = {
          discount: '',
          type: 0
        }
        if (integralType.includes(props.ruleType) || discountType.includes(props.ruleType)) {
          ele.ruleValue[dict.spuId].type = 0
        }
        if (deduType.includes(props.ruleType)) {
          ele.ruleValue[dict.spuId].type = 2
        }
      })
    })
    skusRuleData.value = deepCopyFormData
    let ruleValueData = {}
    if (props.valueType) {
      ruleValueData = formData.value[props.valueType] //规则设置的具体内容
    }
    if (JSON.stringify(ruleValueData) != '{}') {
      // 如果有输入的值就回显

      let arr = objectToArray(ruleValueData)

      arr.forEach((element) => {
        skusRuleData.value.forEach((ele) => {
          if (ele.skuId == element.skuId) ele.ruleValue = element.ruleValue
        })
      })
    } else {
      formData.value[props.valueType] = arrayToObject(skusRuleData.value)
    }
  },
  {
    deep: true,
    immediate: true
  }
)

/** 监听属性列表，生成相关参数和表头 */

watch(
  () => props.propertyList,
  (propertyList: PropertyAndValues[]) => {
    // 如果不是多规格则结束
    if (!formData.value!.specType) {
      return
    }
    // 如果当前组件作为批量添加数据使用，则重置表数据
    if (props.isBatch) {
      skuList.value = [
        {
          ruleValue: {}
        }
      ]
      props.paidMembershipLevelList.forEach((ele) => {
        skuList.value[0]['ruleValue'][ele.spuId] = {
          discount: '',
          type: 0
        }
        if (integralType.includes(props.ruleType) || discountType.includes(props.ruleType)) {
          skuList.value[0]['ruleValue'][ele.spuId].type = 0
        }
        if (deduType.includes(props.ruleType)) {
          skuList.value[0]['ruleValue'][ele.spuId].type = 2
        }
      })
    }

    // 判断代理对象是否为空
    if (JSON.stringify(propertyList) === '[]') {
      return
    }
    // 重置表头
    tableHeaders.value = []
    // 生成表头
    propertyList.forEach((item, index) => {
      // name加属性项index区分属性值
      tableHeaders.value.push({ prop: `name${index}`, label: item.name })
    })
  },
  {
    deep: true,
    immediate: true
  }
)
const activitySkuListRef = ref<InstanceType<typeof ElTable>>()

const getSkuTableRef = () => {
  return activitySkuListRef.value
}
// 暴露出生成 sku 方法，给添加属性成功时调用
defineExpose({ validateSku, getSkuTableRef })
</script>
